Skip to content

Conversation

@mikebaldry
Copy link

Adds support for the number of direct children to be cached on any node without any further lookups.

  acts_as_tree cache_child_count: true

Migration should contain

  t.integer :child_count, null: false, default: 0

@seuros
Copy link
Member

seuros commented Jul 2, 2014

Thank you for your work.
I think we should have test of the counter cache in parallel too because that were the counter cache become corrupt.

@mceachen
Copy link
Collaborator

mceachen commented Jul 2, 2014

Do you have an index on your parent_id column? Getting the child count
should be a really cheap select.

Keeping this column's denormalized value correct will be tricky. You may
want to recalculate it as part of .rebuild!, but even then, that number
will not be reliable without incurring a lot of cost on every
parent-changing write (your parent needs to reload and persist the
child_count column).

Sorry to be negative about this, but I've suffered a lot of pain in the
past from this same sort of column.

@mikebaldry
Copy link
Author

@mceachen Its a really cheap select that adds up when you scale.

Both please bare in mind that this is a core feature of ActiveRecord, I'm not here to retest a core feature of rails. All I've done is basically made sure a parameter is passed through acts_as_tree call.

It doesn't set the counter column based on the value of counter_cache when it loaded, it does it update every time a child is added (UPDATE nodes SET counter_cache = counter_cache + 1 WHERE id = id_of_parent_added_to) I believe databases don't allow 2 things to change the value at the same time, so this should give you a fairly good result. I doubt it would be in ActiveRecord core if it didn't?

@mceachen
Copy link
Collaborator

mceachen commented Dec 9, 2016

Please reopen when tests have been added and conflicts have been resolved. Thanks!

@mceachen mceachen closed this Dec 9, 2016
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants